import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  location: {},
  address: "",
  userInfo:null,
  tempAddress:null,
  token:""  
}

const getters = {
  location: state => state.location,
  address: state => state.address,
  userInfo:state => state.userInfo,
  commonAddress:state => state.userInfo.common_address,
  tempAddress: state => state.tempAddress,
  User:state=>state.userInfo,
  token(state){
    return state.token
  }
}

const mutations = {
  setLocation(state, location) {
    if (location) {
      state.location = location;
    } else {
      location = null
    }
  },

  setAddress(state, address) {
    if (address) {
      state.address = address;
    } else {
      address = ""
    }
  },

  setUserInfo(state,userInfo){
    state.userInfo = userInfo ? userInfo : null;
  },

  setCommonAddress(state,newAddress){
    state.userInfo.common_address.push(newAddress);
  },

  setTempAddress(state,tempAddress){
    state.tempAddress = tempAddress;
  },
  setUser(state,newUserInfo){
    state.userInfo=newUserInfo
  },
  setToken(state,token){
    sessionStorage.setItem("token",token);
    state.token=token
  },
  //直接清空对象
  LOGOUT(state){   
    sessionStorage.clear();
    state.userInfo={};
    state.token=null
  }
}

const actions = {
  setLocation({commit}, location) {
    commit('setLocation',location)
  },

  setAddress({commit}, address) {
    commit('setAddress',address)
  },

  // setUserInfo({commit},userInfo){
  //   commit('setUserInfo',userInfo)
  // },

  setCommonAddress({commit},newAddress){
    commit('setCommonAddress',newAddress)
  },

  setTempAddress({commit},tempAddress){
    commit('setTempAddress',tempAddress)
  },
  setUser({commit},newUserInfo){
    commit('setUser',newUserInfo)
},
}

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})